package com.aidong.pay.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aidong.jobs.async.SmsTask;
import com.aidong.myprofile.dao.MyAppointmentDao;
import com.aidong.pay.biz.OrderManagementBiz;
import com.aidong.pay.dao.OrderManagementDao;
import com.aidong.pay.entity.Recommend;
import com.aidong.stadium.dao.MstScheduleDao;

@Service("orderManagementBiz")
public class OrderManagementBizImpl implements OrderManagementBiz/* , Runnable */ {
    private OrderManagementDao orderManagementDao;
    private MstScheduleDao mstScheduleDao;

    private MyAppointmentDao myAppointmentDao;

    @Autowired
    public void setOrderManagementDao(OrderManagementDao orderManagementDao) {
        this.orderManagementDao = orderManagementDao;
    }


    @Autowired
    public void setMstScheduleDao(MstScheduleDao mstScheduleDao) {
        this.mstScheduleDao = mstScheduleDao;
    }

    @Autowired
    public void setMyAppointmentDao(MyAppointmentDao myAppointmentDao) {
        this.myAppointmentDao = myAppointmentDao;
    }

    @Autowired
    SmsTask smsTask;

    /**
     * 申请退款
     *
     * @param map
     */
    @Override
    public void addApplyOrderRefund(Map<String, Object> map) {
        orderManagementDao.addApplyOrderRefund(map);
    }

    /**
     * 预约状态更改
     *
     * @param map
     */
    @Override
    @Transactional
    public int editAppointStatus(Map<String, Object> map) {
        if (map.containsKey("applyType")) {
            if ("1".equals(map.get("applyType")) || "6".equals(map.get("applyType"))) {
                orderManagementDao.editAppointStatusNew(map);
                //
                map.put("orderType", 1);
                Map<String, Object> resultMap = myAppointmentDao.getCampaginBySubscribeId(map);
                try {
                    String carnivalSubscribeIds = resultMap.get("carnivalSubscribeIds").toString();
                    String[] subIds = carnivalSubscribeIds.split(",");
                    if (subIds.length > 0) {
                        // 取消预约
                        Map<String, Object> appointMap = new HashMap<String, Object>();
                        for (int i = 0; i < subIds.length; i++) {
                            appointMap.clear();
                            appointMap.put("applyType", 1);
                            appointMap.put("status", 1);
                            appointMap.put("subscribeId", subIds[i]);
                            int updateResult = orderManagementDao.editAppointStatus(appointMap);
                            if (updateResult > 0) {
                                orderManagementDao.editCarnivalCampaignIsFull(Integer.valueOf(subIds[i]));
                            }
                        }
                    }

                } catch (Exception e) {

                }
            }
        }
        return orderManagementDao.editAppointStatus(map);
    }

    /**
     * 更改订单状态
     *
     * @param map
     */
    @Override
    public void editOrderPayStatus(Map<String, Object> map) {
        orderManagementDao.editOrderPayStatus(map);
    }

    /**
     * 删除预约记录
     *
     * @param map
     */
    @Override
    public void delAppointStatus(Map<String, Object> map) {
        orderManagementDao.delAppointStatus(map);
    }

    /**
     * 删除订单
     *
     * @param map
     */
    @Override
    public void delOrderPayStatus(Map<String, Object> map) {
        orderManagementDao.delOrderPayStatus(map);
    }

    /**
     * 活动订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, Object> getActiveOrderDetail(int orderId) {
        return orderManagementDao.getActiveOrderDetail(orderId);
    }

    /**
     * 课程订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, Object> getCourseOrderDetail(int orderId) {
        return orderManagementDao.getCourseOrderDetail(orderId);
    }

    @Override
    public void getOrderMessage() {
        try {
            List<Map<String, Object>> payStatus = orderManagementDao.getNoPaymentStatusOrders();
            if (payStatus.size() > 0) {
                for (Map<String, Object> status : payStatus) {
                    String orderId = status.get("orderId").toString(); // 订单号
                    String orderType = status.get("orderType").toString(); // 下单类型//
                    // 1.活动//
                    // 2.课程//
                    // 3.私教
                    String subscribeId = status.get("subscribeId").toString(); // 预约号
                    String payTime = status.get("OrderTime").toString(); // 下单时间
                    try {
                        String carnivalSubscribeIds = status.get("carnivalSubscribeIds").toString();
                        String[] subIds = carnivalSubscribeIds.split(",");
                        if (subIds.length > 0) {
                            // 取消预约
                            Map<String, Object> appointMap = new HashMap<String, Object>();
                            for (int i = 0; i < subIds.length; i++) {
                                appointMap.clear();
                                appointMap.put("applyType", orderType);
                                appointMap.put("status", 1);
                                appointMap.put("subscribeId", subIds[i]);
                                int updateResult = orderManagementDao.editAppointStatus(appointMap);

								/*if (updateResult > 0 && "2".equals(orderType)) {// 取消课程预约
									// 根据预约号查询课程ID
									int autoId = mstScheduleDao.getScheduleAutoId(Integer.valueOf(subIds[i]));
									mstScheduleDao.cutScheduleVersion(autoId);
								} else*/
                                if (updateResult > 0 && "1".equals(orderType)) {

                                    orderManagementDao.editCarnivalCampaignIsFull(Integer.valueOf(subIds[i]));
                                }
                            }
                        }

                    } catch (Exception e) {

                    }
                    int payType = Integer.valueOf(status.get("payType").toString()); // 支付方式
                    // 取消订单
                    Map<String, Object> payMap = new HashMap<String, Object>();
                    payMap.put("status", 3);
                    payMap.put("processId", 4);
                    payMap.put("orderId", orderId);
                    orderManagementDao.editOrderPayStatus(payMap);
                    System.out.println("取消订单操作：参数：" + payMap);

                    // 取消预约
                    Map<String, Object> appointMap = new HashMap<String, Object>();
                    appointMap.put("applyType", orderType);
                    appointMap.put("status", 1);
                    appointMap.put("subscribeId", subscribeId);
                    System.out.println("取消预约操作：预约号：" + subscribeId + "；定案类型：" + orderType);
                    // orderManagementDao.editAppointStatus(appointMap);

                    int updateResult = orderManagementDao.editAppointStatus(appointMap);
                    System.out.println(
                            "===========" + orderType + "--------------" + updateResult + "---------------" + orderId);
                    if (updateResult > 0 && "2".equals(orderType)) {// 取消课程预约
                        // 根据预约号查询课程ID
                        int autoId = mstScheduleDao.getScheduleAutoId(Integer.valueOf(subscribeId));
                        mstScheduleDao.cutScheduleVersion(autoId);
                    } else if (updateResult > 0 && "1".equals(orderType)) {
                        orderManagementDao.editCampaignIsFull(Integer.parseInt(orderId));
                    }

                    // 改电影券改为未使用
                    Map<String, Object> paraMap = new HashMap<String, Object>();
                    paraMap.put("orderId", orderId);
                    orderManagementDao.setMovieTicketsUnuse(paraMap);

                    // 代金券改为未使用
                    orderManagementDao.setCouponsTicketsUnuse(paraMap);

                    // 设置折扣券为未使用
                    if (payType == 7 || payType == 8) {
                        orderManagementDao.setDiscountTicketsUnuse(paraMap);
                    }

                }
            }
            // 课程前15分钟短信提醒
            List<Map<String, Object>> courses = orderManagementDao.getHaveCourseRemindtusNew();
            if (courses.size() > 0) {
                for (Map<String, Object> course : courses) {
                    try {
                        try {
                            String courseDate = course.get("subscribeDate") + " " + course.get("startTime");
                            String cellNumber = course.get("mobilePhone").toString();
                            String storeName = course.get("storeName") + " " + course.get("classroom");
                            String courseName = course.get("courseName").toString();
                            smsTask.courseRemind(cellNumber, courseName, courseDate + "-" + course.get("endTime"),
                                    storeName, "15");
                            // 更改提醒标记位
                            String orderId = course.get("orderId").toString();
                            orderManagementDao.editOrderSmsReminderFlg(orderId);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // }
                }
            }

            // 活动前15分钟短信提醒
            List<Map<String, Object>> activitys = orderManagementDao.getHaveactivityRemindtusNew();
            if (activitys.size() > 0) {
                for (Map<String, Object> activity : activitys) {
                    try {
						/*
						 * SMSUtil.pool.execute(new Runnable() { public void
						 * run() {
						 */
                        try {
                            String campaignDate = activity.get("campaignStartTime").toString();
                            String cellNumber = activity.get("mobilePhone").toString();
                            String placeName = activity.get("placeName").toString();
                            String campaignTitle = activity.get("campaignTitle").toString();
                            smsTask.campaignRemind(cellNumber, campaignTitle, campaignDate, placeName, "15");
                            // 更改提醒标记位
                            String orderId = activity.get("orderId").toString();
                            orderManagementDao.editOrderSmsReminderFlg(orderId);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
						/*
						 * } });
						 */
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改订单信息
     *
     * @param map
     */
    @Override
    public void editOrderPayInfo(Map<String, Object> map) {
        orderManagementDao.editOrderPayInfo(map);
    }

    /**
     * 餐饮订购详情
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, Object> getFoodOrderDetail(int orderId) {
        return orderManagementDao.getFoodOrderDetail(orderId);
    }

    /**
     * 查询订单回调状态
     *
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> getOrderBackStatus(Map<String, Object> map) {
        return orderManagementDao.getOrderBackStatus(map);
    }

    /**
     * 修改订单短信状态
     *
     * @param map
     */
    @Override
    public void editOrderSmsStatus(Map<String, Object> map) {
        orderManagementDao.editOrderSmsStatus(map);
    }

    /**
     * 记录支付回调
     *
     * @param map
     */
    @Override
    public void addPayCallBack(Map<String, Object> map) {
        orderManagementDao.addPayCallBack(map);
    }

    @Override
    /**
     * 兑换券使用
     *
     * @param map
     */
    public void editExchangeTicketsInfo(Map<String, Object> map) {
        orderManagementDao.editExchangeTicketsInfo(map);
    }

    /**
     * 代金券使用
     *
     * @param map
     */
    @Override
    public void editCouponsInfo(Map<String, Object> map) {
        orderManagementDao.editCouponsInfo(map);
    }

    @Override
    public void editexchangeTicketsInfoOrderId(Map<String, Object> map) {
        // TODO Auto-generated method stub
        orderManagementDao.editexchangeTicketsInfoOrderId(map);
    }

    @Override
    public void editCouponsInfoOrderId(Map<String, Object> map) {
        // TODO Auto-generated method stub
        orderManagementDao.editCouponsInfoOrderId(map);
    }

    @Override
    public void editexchangeTicketsInfoOrderIdUse(Map<String, Object> map) {
        // TODO Auto-generated method stub
        orderManagementDao.editexchangeTicketsInfoOrderIdUse(map);
    }

    @Override
    public void editCouponsInfoOrderIdUse(Map<String, Object> map) {
        // TODO Auto-generated method stub
        orderManagementDao.editCouponsInfoOrderIdUse(map);
    }

    /**
     * 设置电影券未被购买
     *
     * @param map
     */
    @Override
    public void setMovieTicketsUnuse(Map<String, Object> map) {
        orderManagementDao.setMovieTicketsUnuse(map);
    }

    /**
     * 设置代金券为未使用
     *
     * @param map
     */
    @Override
    public void setCouponsTicketsUnuse(Map<String, Object> map) {
        orderManagementDao.setCouponsTicketsUnuse(map);
    }

    /**
     * 设置兑换券为未使用
     *
     * @param map
     */
    @Override
    public void setExchangeTicketsUnuse(Map<String, Object> map) {
        orderManagementDao.setExchangeTicketsUnuse(map);
    }

    @Override
    public Map<String, Object> selectMoviceTickets(Map<String, Object> map) {
        // TODO Auto-generated method stub
        return orderManagementDao.selectMoviceTickets(map);
    }

    @Override
    public void editCouponsInfoOrderIdZero(Map<String, Object> map) {
        // TODO Auto-generated method stub
        orderManagementDao.editCouponsInfoOrderIdZero(map);
    }

    @Override
    public void setActivityFlag(int orderId) {
        // TODO Auto-generated method stub
        orderManagementDao.setActivityFlag(orderId);
    }

    @Override
    public Map<String, Object> getCampaignPickUpWay(Map<String, Object> map) {
        // TODO Auto-generated method stub
        return orderManagementDao.getCampaignPickUpWay(map);
    }

    @Override
    public Map<String, Object> getMovieTicketNum(Map<String, Object> map) {
        // TODO Auto-generated method stub
        return orderManagementDao.getMovieTicketNum(map);
    }

    @Override
    public void editDiscountInfoOrderId(Map<String, Object> map) {
        // TODO Auto-generated method stub
        orderManagementDao.editDiscountInfoOrderId(map);
    }

    @Override
    public void editDiscountInfoOrderIdUse(Map<String, Object> map) {
        // TODO Auto-generated method stub
        orderManagementDao.editCouponsInfoOrderIdUse(map);
    }

    @Override
    public void setDiscountTicketsUnuse(Map<String, Object> map) {
        // TODO Auto-generated method stub
        orderManagementDao.setDiscountTicketsUnuse(map);
    }

    @Override
    public Recommend getRecommendInfo(String orderId) {
        return orderManagementDao.getRecommendInfo(orderId);
    }

    public int getLuckyDrawBySubscribeId(Map<String, Object> map) {
        return orderManagementDao.getLuckyDrawBySubscribeId(map);
    }

    /**
     * 预约状态更改
     *
     * @param map
     */
    public int editAppointCampaignStatus(Map<String, Object> map) {
        return orderManagementDao.editAppointStatus(map);
    }
}